package test.transferFile.thread;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import test.transferFile.common.MyFile;

public class TransferFileWorkThread extends Thread {

  private static final int BUFFER_SIZE=1024 * 10;

  private IoSession session;

  private BufferedInputStream in;
  
  private String fileName;

  public TransferFileWorkThread(InputStream in, IoSession session,String fileName) {
    this.in=new BufferedInputStream(in);
    this.session=session;
    this.fileName=fileName;
  }

  @Override
  public void run() {
    byte[] b=new byte[BUFFER_SIZE];
    int len=0;
    int pos=0;
    try {
      while((len=in.read(b)) != -1) {
        // 读取一段文件数据
        IoBuffer data=IoBuffer.allocate(len);
        data.put(b, 0, len);
        data.flip();
        System.out.println("拆分包:" + data);
        // obj
        MyFile myFile=new MyFile();
        myFile.setName(fileName);
        myFile.setLength(len);
        myFile.setPos(pos);
        pos+=len;
        myFile.setData(data);
        session.write(myFile);
//        sleep(5);
      }
    } catch(IOException e) {
      e.printStackTrace();
//    } catch(InterruptedException e) {
//      e.printStackTrace();
    } finally {
      if(in!=null){
        System.out.println("close read io");
        try {
          in.close();
        } catch(IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }

  public void setIn(BufferedInputStream in) {
    this.in=in;
  }

  public BufferedInputStream getIn() {
    return in;
  }
}
